<?php

namespace app\modules\prod\controllers;

use yii;
use yii\helpers\Json;
use app\common\Controller;
use app\common\SystemEvent;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii2mod\editable\EditableAction;
use yii2mod\rbac\filters\AccessControl;
use app\models\Region;
use app\models\RegionType;
use yii\data\Pagination;
use yii\data\ActiveDataProvider;


class RegionController extends Controller
{
    
	public $module;
	public $protected_uids = [];    
	public $superadmin_uid = 0;
	public $loginRedirect = '/admin/dashboard';
	public $defaultAction = 'index';
	public function init()
	{
		parent::init();
	}


     public function actionIndex()
    {
        $query = Region::find();//内置函数找到Region表
        $pagination = new Pagination([//new Pagination定义分页
            'defaultPageSize' => 5,//每页5条
            'totalCount' => $query->count(),//总数
        ]);
        $regions = $query->orderBy('region_type_id')->offset($pagination->offset)->limit($pagination->limit)->all();
        return $this->render('index', ['pagination' => $pagination ,
        'regions' => $regions ]);

    }

    public function actionView($id=null, $region_type_id=null, $region_name=null)
    {
        $query = Region::find();
        $query->where(['parent_region_id' => $id ]);
       $query->orderBy('id');

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);
        


        return $this->render('classify',
            ['dataProvider' => $dataProvider ,
//                'regions' => $regions,
                'parent_region_id' => $id,
                'region_type_id' => $region_type_id,
                'create_type' => 1, // 创建类型为1 代表创建子集
                'region_type_name' => '下级区域',
                'region_name' => $region_name]);

        //$query->andFilterWhere(['parent_region_id' => $id]);
    }

    public function actionClassify($region_type_id=null)
    {
        // c初始化区域类型
        if ($region_type_id==null)
        {
            $region_type_id = 2;
        }
       // $region_type_id = 2;
        $region_type_name = "找不到需要创建的区域";

        $query = Region::find();
//        $pagination = new Pagination([
//            'defaultPageSize' => 5,
//            'totalCount' => $query->count(),
//        ]);
        $query->where(['region_type_id' => $region_type_id ]);
        $query->orderBy('id');
        $dataProvider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
                'pageSize' => 20,
            ],
        ]);

        // 通过添加过滤器来调整查询语句
        //$query->andFilterWhere(['region_type_id' => $region_type_id]);

       // $regions = $query->where('region_type_id=:region_type_id', [':region_type_id' => $region_type_id ])->orderBy('id')->all();

        switch($region_type_id )
        {
            case 2://省
                $region_type_name = 'Provine';
                break;
            case 3://市
                $region_type_name = 'City';
                break;
            case 4://区
                $region_type_name = 'Area';
                break;
            case 6://直辖市
                $region_type_name = 'Municipality';
                break;
            default:
                break;
        }



        return $this->render('classify',
            ['dataProvider' => $dataProvider ,
//                'regions' => $regions,

                'region_type_id' => $region_type_id,
                'region_type_name' => $region_type_name]);

    }

    // 创建子集
    //public function actionCreateSub($region_type_id=null,$region_type_name=null)

    public function actionCreate($region_type_id=null,$region_type_name=null, $parent_region_id=null)
    {
        //Yii::trace("=================================");
        // Yii::trace($parent_region_id);
        // 初始化类型
        if ($region_type_id==null)
        {
            $region_type_id = '';
        }

        if ($region_type_name==null)
        {
            $region_type_name = '';
        }

        if ($parent_region_id==null)
        {
            $parent_region_id = 0;
        }

        $model = new Region();


        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
          //  Yii::trace("=====================");
          //  Yii::trace(Yii::$app->request->post());
          //  Yii::trace($model);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));
            if ($parent_region_id==0)
            {
                $model->region_type_id    = $region_type_id;
            }
           //
           // $model->parent_region_id  = 0;
            $model->create_date        = date("Y-m-d H:i:s",time());;
            $model->create_staff_id   = Yii::$app->user->id;
            $model->modify_date        = date("Y-m-d H:i:s",time());;
            $model->modify_staff_id   = Yii::$app->user->id;
            $model->state               = 'ON';

            //创建Region
            $this->insertOrUpdateToRegionTable($model);
            return $this->redirect(['view','id' =>$parent_region_id, 'region_type_id' => $region_type_id, 'region_name' => $model->region_name]);
           // return   $this->redirect(Yii::app()->request->urlReferrer);
           // return  $this->redirect(Yii::$app->request->getReferrer());
            //return $this->redirect(['classify', 'region_type_id' => $region_type_id, 'region_type_name' => $region_type_name]);
        }

       // $query = RegionType::find();
       // $regionTypes = $query->orderBy('id')->all();

        // 查询所有该区域的子集

        $queryRegionType = RegionType::find();
        $regionTypes = $queryRegionType->where(['parent_region_id' => $region_type_id ])->all();

        return $this->render('create', ['model' => $model, 'regionTypes' =>$regionTypes, 'parentRegionId' =>$parent_region_id]);

        // render
        //  return $this->render('create');

    }

    /**
     * 新增或者修改 role table
     * @param $newRole
     * @param string $oldRole
     */
    public function insertOrUpdateToRegionTable( $newRegion, $oldRegion="")
    {
        //$should = 0;//1=insert,2=update,0=nothing to do
        //$role   = null;
        if($oldRegion)
        {

        }
        else
        {
            //新增
            /*$role = Region::find()->where(['name'=>$newRegion])->one();
            if(!$role){
                $should = 1;
            }*/
            $newRegion->save();
        }



    }

//    public function actionIndex()
//    {
//        $menus = SystemEvent::GetAdminMenu();
//        if(Yii::$app->request->isAjax){
//            return '<script>OA_Menus='.Json::encode($menus).'</script>';
//        }
//        return $this->renderPartial('index',['menus'=>$menus]);
//    }
}
